$(function (){
	$.init();
	var param = parseUrlSearch();
	$(document).on('click', '.btn-save', onSave);
	$(document).on('click', '.j-return', onBack);

	$("#area").cityPicker({
		toolbarTemplate: '<header class="bar bar-nav">\
							<button class="button button-link pull-right close-picker">确定</button>\
							<h1 class="title">选择所在地区</h1>\
						</header>'
	});

	renderInfo();
	
	function renderInfo () {
		fetchAddress(function (data) {
			if(data.addressInfo) {
				data = JSON.parse(data.addressInfo);
				$('#name').val(data.name);
				$('#phone').val(data.phone);
				$('#area').val(data.area);
				$('#address').val(data.address);
			}
		});
	}

	function fetchAddress (callback) {
		$.ajax({
			url: HOST + '/api/user/address/get',
			data: {
				openid: SELFID
			},
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function onSave () {
		var data = collect();
		if(validate(data)){
			saveAddress(data, function (){
				$.alert('编辑地址成功', function () {
					onBack();
				});
			});
		}
	}

	function collect () {
		var address = {};
		address['name'] = $('#name').val();
		address['phone'] = $('#phone').val();
		address['area'] = $('#area').val();
		address['address'] = $('#address').val();
		return address;
	}

	function validate (data) {
		for (var key in data){
			if(!data[key]) {
				$.alert('请填写完再提交哟！');
				return false;
			}
		}
		return true;
	}

	function saveAddress (data, callback) {
		$.ajax({
			url: HOST + '/api/user/address/update',
			data: JSON.stringify({
				openid: SELFID,
				addressInfo: JSON.stringify(data)
			}),
			type: 'POST',
			success: function(res) {
				if(res.content == 'success') {
					callback && callback();
				}	
			}
		});
	}

	function onBack () {
		var params = param.from.split('|');
		if(params[params.length-1] == 'car') {
			window.location = './product_car.html';
		}else if(params[params.length-1] == 'sure') {
			window.location = './product_sure.html?from='+params[0];
		}
	}
});
